﻿package com.kucooler.fog.control {
	import com.kucooler.fog.core.MvcLocator;
	import com.kucooler.fog.core.Notifier;
	import com.kucooler.fog.core.INotifier;
	import com.kucooler.fog.core.Observer;
	import com.kucooler.fog.core.IObserver;
	import com.kucooler.fog.utils.mvcError;
	import com.kucooler.fog.utils.PaperLogger;
	/**
	* 命令控制器
	* <p>
	* <ul>
	* <li>添加、移除命令</li>
	* </ul>
	* </p>
	*/
	public class Controller extends MvcLocator implements IController {
		static private var m_instance:Controller = null;
		protected var m_notifier:INotifier = Notifier.getInstance();
		
		public function Controller() {
			if (m_instance != null) {
				throw new mvcError(mvcError.SINGLETON_CONTROLLER_MSG, Controller);
			}			
		}
		
		static public function getInstance():IController {
			if (m_instance == null) {
				m_instance = new Controller();
			}
			return m_instance;
		}
		
		/**
		 * 添加命令,将命令添加到列表
		 * @param	commandName Class 命令类
		 */
		public function addCommand(commandName:Class):void {
			if (!hasExists(commandName)) {
				var oberver:IObserver = new Observer(executeCommand, this);  //实例化观察者,传递回调函数,函数执行域
				//将观察者添加到通知列表中
				m_notifier.addObserver(commandName, oberver); 
				//将命令添加到列表
				add(commandName, commandName);
			}else {
				PaperLogger.getInstance().log(mvcError.ADD_COMMAND_MSG, Controller, commandName);
			}
		}
		
		/**
		 * 移除命令
		 * @param	commandName Class 命令类
		 */
		public function removeCommand(commandName:Class):void {
			if (hasExists(commandName)) {
				m_notifier.removeObserver(commandName, this); //将观察者从通知列表中移除
				remove(commandName);  //从列表中移除命令
			}else {
				PaperLogger.getInstance().log(mvcError.REMOVE_COMMAND_MSG, Controller, commandName);
			}
		}
		
		/**
		 * 判断此命令是否已经存在
		 * @param	commandName Class 命令类
		 * @return  Boolean			  是否存在
		 */
		public function hasCommand(commandName:Class):Boolean {
			return hasExists(commandName);
		}
		
		/**
		 * 执行此命令
		 * @param	commandName Class   命令类
		 * @param	data Objcet 		实例化此命令类时所带的参数
		 */
		public function executeCommand(commandName:Class, data:Object = null):void {
			if (hasExists(commandName)) {
				var commandClass:Class = retrieve(commandName);
				var commandInstance:ICommand = new commandClass();
				commandInstance.execute(data);
			}else {
				PaperLogger.getInstance().log(mvcError.COMMAND_NOT_FOUND, Controller, commandName);
			}
		}
	}
}
